﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using libManagedMessageSystem;

namespace ManagedEchoClient
{
    class Packet : Message
    {
        public Int32 a;
        public float b;
        public String s;
        public UInt32 c;

        public override void Read(NetStream stream)
        {
            a = stream.ReadInt32();
            b = stream.ReadFloat();
            s = stream.ReadString();
            c = stream.ReadUInt32();
        }

        public override void Write(NetStream stream)
        {
            stream.WriteInt32(a);
            stream.WriteFloat(b);
            stream.WriteString(s);
            stream.WriteUInt32(c);
        }
    }

    class TestMessageHandler : IMessageHandler
    {
        public virtual void OnLost()
        {
            Console.WriteLine("OnLost");
        }

        public virtual void OnMsg(MessageChannel mc,UInt16 nDispatchId,UInt16 nMessageId, NetStream ns)
        {
            switch (nMessageId)
            {
                case 1:
                    {
                        break;
                    }
                case 2:
                    {
                        Packet p = new Packet();
                        p.Read(ns);
                        Console.WriteLine("a={0},b={1},c={2}", p.a, p.b, p.s);
                        break;
                    }
            }
        }
    }

    class Program
    {
        public static void OnConnectSuccess(MessageChannel mc)
        {            
            Console.WriteLine("OnConnectSuccess");
            mc.Open(new TestMessageHandler());

            UInt16[] buf = new UInt16[10];
            for (int i = 0; i < 10; ++i)
            {
                buf[i] = (UInt16)i;
            }

            Packet p = new Packet();
            p.a = 10;
            p.b = 12121212.0f;
            p.s = "hello world";
            p.c = 110;
            mc.Send(p,2,1);
            mc.BroadCast(p, 2, buf,(UInt16)buf.Length);
        }

        public static void OnConnectFailed(Int32 ec)
        {
            Console.WriteLine("OnConnectFailed");
        }

        static void Main(string[] args)
        {
            try
            {
                MessageSystem ms = new MessageSystem();
                ms.ConnectRemoteSystem("127.0.0.1", 5000, OnConnectSuccess, OnConnectFailed);
                while (true)
                {
                    ms.Poll(1000);                    
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.ReadLine();
        }
    }
}
